package com.xhorse.lockplatform.comm.util;

import com.xhorse.lockplatform.comm.enums.LogModuleEnum;
import org.assertj.core.util.Preconditions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;

/**
 * 日志统计类，用于做页面访问以日志形式进行记录统计
 *
 * @author Tom
 */
public final class LogStatistics {
    private static final Logger log = LoggerFactory.getLogger(LogStatistics.class);
    private static final char SEP = ' ';

    private LogStatistics() {
    }

    public static void log(LogModuleEnum module, String identity, String msg) {
        Preconditions.checkNotNull(module);
        Preconditions.checkNotNull(identity);
        StringBuilder builder = new StringBuilder();
        builder.append(module).append(SEP)
                .append(identity).append(SEP)
                .append(System.currentTimeMillis()).append(SEP);
        append(builder, msg);
        log.info(msg);
    }

    public static void log(LogModuleEnum module, HttpServletRequest request, Object... segments) {
        log(log, module, true, request, segments);
    }

    public static void log(LogModuleEnum module, boolean needQueryString, HttpServletRequest request,
                           Object... segments) {
        log(log, module, needQueryString, request, segments);
    }

    public static void log(Logger logger, LogModuleEnum module, boolean needQueryString,
                           HttpServletRequest request, Object... segments) {
        Preconditions.checkNotNull(module);
        StringBuilder msg = new StringBuilder();
        msg.append(module).append(SEP)
                .append(DateUtils.formatNowToMinute()).append(SEP);
//        String ip = RequestUtils.getRemoteIp(request);
//        IpSeeker.IpData ipData = IpSeeker.ipData(ip);
//        append(msg, ip).append(SEP).append(ipData == null ? "cn" : ipData.shortcut).append(SEP);
        append(msg, request.getRequestURI());
        if (needQueryString && request.getQueryString() != null) {
            msg.append("?").append(request.getQueryString());
        }
        if (segments != null) {
            for (Object segment : segments) {
                msg.append(SEP).append(segment == null ? "" : segment);
            }
        }
        logger.info(msg.toString());
    }


    private static StringBuilder append(StringBuilder builder, String msg) {
        if (msg != null) {
            builder.append(msg);
        }
        return builder;
    }
}
